package com.trendata.mina.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.trendata.mina.factory.CharsetCodecFactory;
import com.trendata.mina.handler.ServerMessageHandler;

public class MinaServer {
	private Logger logger = Logger.getLogger("serverSocketLogger");
	private SocketAcceptor acceptor;

	public MinaServer() {
		logger.info("创建非阻塞的server端的Socket连接");
		acceptor = new NioSocketAcceptor();
	}

	public boolean start() {
		logger.info("服务器启动");
		DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
		logger.info("添加编码过滤器 处理乱码、编码问题");
		filterChain.addLast("codec", new ProtocolCodecFilter(new CharsetCodecFactory()));
		logger.info("设置核心消息业务处理器");
		acceptor.setHandler(new ServerMessageHandler());
		logger.info("设置session配置，30秒内无操作进入空闲状态");
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
		int bufferSize = 5000000;
		logger.info("设置session配置，读取缓存为:" + bufferSize);
		acceptor.getSessionConfig().setReadBufferSize(bufferSize);
		logger.info("设置session配置，最大读取缓存为:" + bufferSize);
		acceptor.getSessionConfig().setMaxReadBufferSize(bufferSize);
		logger.info("设置session配置，最大接收缓存为:" + bufferSize);
		acceptor.getSessionConfig().setReceiveBufferSize(bufferSize);
		try {
			acceptor.bind(new InetSocketAddress(9999));
			logger.info("绑定端口9999");
		} catch (IOException e) {
			logger.error("绑定端口出现异常：" + e.getMessage());
			return false;
		}
		return true;
	}

	public static void main(String[] args) {
		MinaServer server = new MinaServer();
		server.start();
	}
}
